# -*- coding: UTF-8 -*-
import platform
import os
import shutil
import sys
import time
import math
import json
import zipfile


sys.path.append("..")
sys.path.append("../Helper")
sys.path.append("../Utils")
sys.path.append("../Encrypt")

import FileUtils
import CommonUtils
from VersionHelper import VersionHelper
from FileMD5Helper import FileMD5Helper
from DiffMD5Helper import DiffMD5Helper
from VersionListHelper import VersionListHelper
from ZipPackHelper import ZipPackHelper



Cur_Path = os.getcwd()
Game_Path = os.path.join(Cur_Path,"game")
Md5_Dir_Path = os.path.join(Game_Path,"md5")
Version_List_File_Path = os.path.join(Game_Path,"versionList.json")
Version_File_Path = os.path.join(Cur_Path,"version.txt")


#热更总控制脚本
class HotUpdateHelper:
	def __init__(self):
		self.config = FileUtils.getJsonFileData(os.path.join(Cur_Path,"config.json"))
		# print("self.config = ",self.config)
		self._VersionHelper = VersionHelper(Version_File_Path)
		self._FileMD5Helper = FileMD5Helper()
		pass

	def initTargetDirMD5(self):
		need_hot_update_dir = self.config["need_hot_update_dir"]['path']

		for relativePath in need_hot_update_dir:  

			path1 = os.path.join(Cur_Path,relativePath)
			# print("dirname = ",dirname)
			self._FileMD5Helper.addAllFileMD5ByPath(path1)

		pass

	#保存第一个版本的MD5
	def saveFirstVersionMD5(self):
		_versionStr = self._VersionHelper.getVersionStr()
		_versionMap = self._FileMD5Helper.getMD5Map()
		_path = os.path.join(Md5_Dir_Path,_versionStr +".json")
		FileUtils.writeJsonToFile(_path,_versionMap)
		pass

	def saveVersionListFile(self):
		_versionStr = self._VersionHelper.getVersionStr()
		FileUtils.writeJsonToFile(Version_List_File_Path,[_versionStr])
		pass

	def addVersionToVersionListFile(self):
		_versionStr = self._VersionHelper.getVersionStr()
		data = FileUtils.getJsonFileData(Version_List_File_Path)
		data.append(_versionStr)
		FileUtils.writeJsonToFile(Version_List_File_Path,data)
		pass

	def initVersion(self):
		#初始化版本帮助类
		self.initTargetDirMD5()
		#保存版本MD5
		self.saveFirstVersionMD5()
		self.encry()
		self.saveVersionListFile()
		pass
		
	def autoAddVersion(self):
		self._VersionHelper.addSmallVersion()


	def diffVersionMD5AndPackageZip(self):
		os.chdir(Cur_Path)
		
		self._VersionListHelper = VersionListHelper(Version_List_File_Path)
		
		_versionList = self._VersionListHelper.getVersionList()
		self._DiffMD5Helper = DiffMD5Helper(self._VersionHelper.getVersionStr())
		_allDiffMap = self._DiffMD5Helper.diffVersionFile(_versionList,Md5_Dir_Path)
		print("_allDiffMap = ",_allDiffMap)


		self._ZipPackHelper = ZipPackHelper()
		rootPath = self.config["need_hot_update_dir"]["rootPath"]
		absRootPath = os.path.abspath(os.path.join(Cur_Path,rootPath))
		zipRootPath = self.config["hot_update_path"]["zipRootPath"]

		for versionStr in _allDiffMap:
			diffFileMap = _allDiffMap[versionStr]
			_fileList = []
			versionDir = os.path.join(zipRootPath,self._VersionHelper.getVersionStr())
			diffVersionDir = os.path.join(versionDir,versionStr)
			FileUtils.makedirs(diffVersionDir)
			zipName = versionStr + ".zip"
			zipFilePath = os.path.join(diffVersionDir,zipName)
			for fileRelativePath in diffFileMap:
				_filePath = os.path.join(rootPath,fileRelativePath)
				_fileAbsPath = os.path.abspath(_filePath)
				_fileList.append(_fileAbsPath)
			self._ZipPackHelper.pack(_fileList,zipFilePath,absRootPath)

			sizeDic = {}
			sizeDic["size"] = FileUtils.getFileSize(zipFilePath)
			jsonPath = os.path.join(diffVersionDir,versionStr + ".json")
			FileUtils.writeJsonToFile(jsonPath,sizeDic)
		#直接把需要打包的文件打包成压缩包
		pass

	#打热更
	def packageHotUpdate(self):
		#版本自增
		self.autoAddVersion()
		#生成当前版本的MD5
		self.initTargetDirMD5()
		self.saveFirstVersionMD5()
		self.addVersionToVersionListFile()
		self.encry()
		#当前版本的MD5,对比历史版本的MD5,记录差异
		self.diffVersionMD5AndPackageZip()
		#根据差异,生成对应的版本压缩包(路径 : 当前版本/历史版本/zip,当前版本/历史版本/size.json)
		pass

	def encry(self):
		print("========== 加密开始 ============")
		_path = os.path.join(Cur_Path,"../Encrypt")
		os.chdir(_path)
		CommonUtils.sys("python3 mainAutoEncry.py")

	#重置环境
	def resetVersion(self):
		#删除game下面的所有文件
		CommonUtils.sys("rm -rf " + os.path.join(Cur_Path,"game/"))
		#重置版本为1.0.0
		self._VersionHelper.resetVersion()
		#写入版本
		self._VersionHelper.saveVersion(Version_File_Path)
		pass


	def printVersion(self):
		print("version : ",self._VersionHelper.getVersionStr())


